package com.hb.umsp.contraller;

import com.github.pagehelper.PageInfo;
import com.hb.umsp.entity.HbQuestionBank;
import com.hb.umsp.service.QuestionBankService;
import com.hb.umsp.util.ExcelUtils;
import com.hb.umsp.util.JsonResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@CrossOrigin("*")
@RestController
@RequestMapping("/question")
public class QuestionBankController {

    @Autowired
    QuestionBankService questionBankService;

    Logger logger = LoggerFactory.getLogger(QuestionBankController.class);

    @PostMapping("/import")
    public JsonResult<String> readExcel(@RequestBody MultipartFile file){
        long t1 = System.currentTimeMillis();
        logger.info("上传的文件："+file);
        List<HbQuestionBank> list = ExcelUtils.readExcel("", HbQuestionBank.class, file);
        long t2 = System.currentTimeMillis();
        logger.info(String.format("read over! cost:%sms", (t2 - t1)));
        questionBankService.saveQuestionAndAns(list);

        return new JsonResult<>("20000","导入成功");
    }

    @RequestMapping("/questionList")
    public JsonResult selectQuestionAndAns(@RequestParam(defaultValue = "1") int pageNum,
                                           @RequestParam(defaultValue = "5" ) int pageSize,
                                           HttpServletRequest request,
                                           @RequestBody(required = false) HbQuestionBank hbQuestionBank){
        String token = request.getHeader("token");
        if (token == null || "".equals(token)) {
            return new JsonResult("50008","未获取token");
        }
        PageInfo<HbQuestionBank> page = questionBankService.selectQuestionAndAns(pageNum,pageSize,token,hbQuestionBank);

        return new JsonResult("20000",page);
    }
}
